<!doctype html>




<html class="theme-next pisces" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
    
  
  <link href="//cdn.staticfile.org/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.lug.ustc.edu.cn/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//cdn.staticfile.org/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Web,JavaScript," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="选择符API众多JavaScript 库中最常用的一项功能，就是根据CSS 选择符选择与某个模式匹配的DOM 元素。实际上，jQuery(www.jquery.com)的核心就是通过CSS 选择符查询DOM文档取得元素的引用，从而抛开了getElementById()和getElementsByTagName()。
Selectors API Level 1 的核心是两个方法：querySelec">
<meta property="og:type" content="article">
<meta property="og:title" content="《 JavaScript 高级程序设计》备忘-第十一章-1">
<meta property="og:url" content="http://codingme.xyz/2016/10/04/javascript-note-11-1/index.html">
<meta property="og:site_name" content="CodingMe">
<meta property="og:description" content="选择符API众多JavaScript 库中最常用的一项功能，就是根据CSS 选择符选择与某个模式匹配的DOM 元素。实际上，jQuery(www.jquery.com)的核心就是通过CSS 选择符查询DOM文档取得元素的引用，从而抛开了getElementById()和getElementsByTagName()。
Selectors API Level 1 的核心是两个方法：querySelec">
<meta property="og:updated_time" content="2016-10-18T06:23:42.060Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="《 JavaScript 高级程序设计》备忘-第十一章-1">
<meta name="twitter:description" content="选择符API众多JavaScript 库中最常用的一项功能，就是根据CSS 选择符选择与某个模式匹配的DOM 元素。实际上，jQuery(www.jquery.com)的核心就是通过CSS 选择符查询DOM文档取得元素的引用，从而抛开了getElementById()和getElementsByTagName()。
Selectors API Level 1 的核心是两个方法：querySelec">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"right","display":"post"},
    fancybox: true,
    motion: false,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://codingme.xyz/2016/10/04/javascript-note-11-1/"/>





  <title> 《 JavaScript 高级程序设计》备忘-第十一章-1 | CodingMe </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">CodingMe</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="http://codingme.xyz/2016/10/04/javascript-note-11-1/">

  <span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="name" content="Huang SJ">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/uploads/avatar.jpg">
  </span>

  <span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="CodingMe">
    <span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="CodingMe" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                《 JavaScript 高级程序设计》备忘-第十一章-1
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            

            

            
          </span>

          

          
            
          

          

          
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="选择符API"><a href="#选择符API" class="headerlink" title="选择符API"></a>选择符API</h1><p>众多JavaScript 库中最常用的一项功能，就是根据CSS 选择符选择与某个模式匹配的DOM 元素。<br>实际上，jQuery(www.jquery.com)的核心就是通过CSS 选择符查询DOM文档取得元素的引用，从而抛开了getElementById()和getElementsByTagName()。</p>
<p>Selectors API Level 1 的核心是两个方法：querySelector()和querySelectorAll()。<br>在兼容的浏览器中，可以通过Document 及Element 类型的实例调用它们。<br>目前已完全支持Selectors API Level 1的浏览器有IE 8+、Firefox 3.5+、Safari 3.1+、Chrome 和Opera 10+。</p>
<h2 id="querySelector-方法"><a href="#querySelector-方法" class="headerlink" title="querySelector()方法"></a>querySelector()方法</h2><p>querySelector()方法接收一个CSS 选择符，返回与该模式匹配的第一个元素，如果没有找到匹配的元素，返回null。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//取得body 元素</span></div><div class="line"><span class="keyword">var</span> body = <span class="built_in">document</span>.querySelector(<span class="string">"body"</span>);</div><div class="line"><span class="comment">//取得ID 为"myDiv"的元素</span></div><div class="line"><span class="keyword">var</span> myDiv = <span class="built_in">document</span>.querySelector(<span class="string">"#myDiv"</span>);</div><div class="line"><span class="comment">//取得类为"selected"的第一个元素</span></div><div class="line"><span class="keyword">var</span> selected = <span class="built_in">document</span>.querySelector(<span class="string">".selected"</span>);</div><div class="line"><span class="comment">//取得类为"button"的第一个图像元素</span></div><div class="line"><span class="keyword">var</span> img = <span class="built_in">document</span>.body.querySelector(<span class="string">"img.button"</span>);</div></pre></td></tr></table></figure>
<a id="more"></a>
<p>通过Document 类型调用querySelector()方法时，会在文档元素的范围内查找匹配的元素。<br>而通过Element 类型调用querySelector()方法时，只会在该元素后代元素的范围内查找匹配的元素。<br>如果传入了不被支持的选择符，querySelector()会抛出错误。</p>
<h2 id="querySelectorAll-方法"><a href="#querySelectorAll-方法" class="headerlink" title="querySelectorAll()方法"></a>querySelectorAll()方法</h2><p>接收的参数与querySelector()方法一样，都是一个CSS 选择符，但返回的是所有匹配的元素而不仅仅是一个元素。返回的是一个NodeList 的实例。<br>具体来说，返回的值实际上是带有所有属性和方法的NodeList，而其底层实现则类似于一组元素的<strong>快照</strong>，而非不断对文档进行搜索的动态查询。<br>可以避免使用NodeList 对象通常会引起的大多数性能问题。<br>只要传给querySelectorAll()方法的CSS 选择符有效，该方法都会返回一个NodeList 对象，而不管找到多少匹配的元素。<br>如果没有找到匹配的元素，NodeList 就是空的。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//取得某&lt;div&gt;中的所有&lt;em&gt;元素(类似于getElementsByTagName("em"))</span></div><div class="line"><span class="keyword">var</span> ems = <span class="built_in">document</span>.getElementById(<span class="string">"myDiv"</span>).querySelectorAll(<span class="string">"em"</span>);</div><div class="line"><span class="comment">//取得类为"selected"的所有元素</span></div><div class="line"><span class="keyword">var</span> selecteds = <span class="built_in">document</span>.querySelectorAll(<span class="string">".selected"</span>);</div><div class="line"><span class="comment">//取得所有&lt;p&gt;元素中的所有&lt;strong&gt;元素</span></div><div class="line"><span class="keyword">var</span> strongs = <span class="built_in">document</span>.querySelectorAll(<span class="string">"p strong"</span>);</div></pre></td></tr></table></figure>
<p>与querySelector()类似，如果传入了浏览器不支持的选择符或者选择符中有语法错误，querySelectorAll()会抛出错误。</p>
<h2 id="matchesSelector-方法"><a href="#matchesSelector-方法" class="headerlink" title="matchesSelector()方法"></a>matchesSelector()方法</h2><p>Selectors API Level 2 规范为Element 类型新增了一个方法matchesSelector()。<br>这个方法接收一个参数，即CSS 选择符，如果调用元素与该选择符匹配，返回true；否则，返回false。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (<span class="built_in">document</span>.body.matchesSelector(<span class="string">"body.page1"</span>))&#123;</div><div class="line">    <span class="comment">//true</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>在取得某个元素引用的情况下，使用这个方法能够方便地检测它是否会被querySelector()或querySelectorAll()方法返回。<br>截至2011 年年中，还没有浏览器支持matchesSelector()方法；<br>不过，也有一些实验性的实现。IE 9+通过msMatchesSelector()支持该方法，Firefox 3.6+通过mozMatchesSelector()支持该方法，Safari 5+和Chrome 通过webkitMatchesSelector()支持该方法。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">matchesSelector</span>(<span class="params">element, selector</span>)</span>&#123;</div><div class="line">    <span class="keyword">if</span> (element.matchesSelector)&#123;</div><div class="line">        <span class="keyword">return</span> element.matchesSelector(selector);</div><div class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (element.msMatchesSelector)&#123;</div><div class="line">        <span class="keyword">return</span> element.msMatchesSelector(selector);</div><div class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (element.mozMatchesSelector)&#123;</div><div class="line">        <span class="keyword">return</span> element.mozMatchesSelector(selector);</div><div class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (element.webkitMatchesSelector)&#123;</div><div class="line">        <span class="keyword">return</span> element.webkitMatchesSelector(selector);</div><div class="line">    &#125; <span class="keyword">else</span> &#123;</div><div class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">"Not supported."</span>);</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="keyword">if</span> (matchesSelector(<span class="built_in">document</span>.body, <span class="string">"body.page1"</span>))&#123;</div><div class="line">    <span class="comment">//执行操作</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h1 id="元素遍历"><a href="#元素遍历" class="headerlink" title="元素遍历"></a>元素遍历</h1><p>对于元素间的空格，IE9 及之前版本不会返回文本节点，而其他所有浏览器都会返回文本节点。<br>这样，就导致了在使用childNodes 和firstChild 等属性时的行为不一致。<br>为了弥补这一差异，而同时又保持DOM规范不变，Element Traversal 规范(www.w3.org/TR/ElementTraversal/)新定义了一组属性。</p>
<ul>
<li>childElementCount：返回子元素(不包括文本节点和注释)的个数。</li>
<li>firstElementChild：指向第一个子元素；firstChild 的元素版。</li>
<li>lastElementChild：指向最后一个子元素；lastChild 的元素版。</li>
<li>previousElementSibling：指向前一个同辈元素；previousSibling 的元素版。</li>
<li>nextElementSibling：指向后一个同辈元素；nextSibling 的元素版。</li>
</ul>
<p>利用这些元素不必担心空白文本节点，从而可以更方便地查找DOM 元素。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//原版本</span></div><div class="line"><span class="keyword">var</span> i,</div><div class="line">len,</div><div class="line">child = element.firstChild;</div><div class="line"><span class="keyword">while</span>(child != element.lastChild)&#123;</div><div class="line">    <span class="keyword">if</span> (child.nodeType == <span class="number">1</span>)&#123; <span class="comment">//检查是不是元素</span></div><div class="line">        processChild(child);</div><div class="line">    &#125;</div><div class="line">    child = child.nextSibling;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">//而使用Element Traversal 新增的元素，代码会更简洁。</span></div><div class="line"><span class="keyword">var</span> i,</div><div class="line">len,</div><div class="line">child = element.firstElementChild;</div><div class="line"><span class="keyword">while</span>(child != element.lastElementChild)&#123;</div><div class="line">processChild(child); <span class="comment">//已知其是元素</span></div><div class="line">child = child.nextElementSibling;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>支持Element Traversal 规范的浏览器有IE 9+、Firefox 3.5+、Safari 4+、Chrome 和Opera 10+。</p>
<h1 id="HTML5"><a href="#HTML5" class="headerlink" title="HTML5"></a>HTML5</h1><p>对于传统HTML 而言，HTML5 是一个叛逆。<br>所有之前的版本对JavaScript 接口的描述都不过三言两语，主要篇幅都用于定义标记，与JavaScript 相关的内容一概交由DOM 规范去定义。</p>
<p>而HTML5 规范则围绕如何使用新增标记定义了大量JavaScript API。其中一些API 与DOM 重叠，定义了浏览器应该支持的DOM扩展。</p>
<h2 id="与类相关的扩充"><a href="#与类相关的扩充" class="headerlink" title="与类相关的扩充"></a>与类相关的扩充</h2><p>HTML5 新增了很多API，致力于简化CSS 类的用法。</p>
<h3 id="getElementsByClassName-方法"><a href="#getElementsByClassName-方法" class="headerlink" title="getElementsByClassName()方法"></a>getElementsByClassName()方法</h3><p>是最受人欢迎的一个方法，可以通过document对象及所有HTML 元素调用该方法。<br>这个方法最早出现在JavaScript 库中，是通过既有的DOM 功能实现的，而原生的实现具有极大的性能优势。<br>getElementsByClassName()方法接收一个参数，即一个包含一或多个类名的字符串，返回带有指定类的所有元素的NodeList。<br>传入多个类名时，类名的先后顺序不重要。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//取得所有类中包含"username"和"current"的元素，类名的先后顺序无所谓</span></div><div class="line"><span class="keyword">var</span> allCurrentUsernames = <span class="built_in">document</span>.getElementsByClassName(<span class="string">"username current"</span>);</div><div class="line"><span class="comment">//取得ID 为"myDiv"的元素中带有类名"selected"的所有元素</span></div><div class="line"><span class="keyword">var</span> selected = <span class="built_in">document</span>.getElementById(<span class="string">"myDiv"</span>).getElementsByClassName(<span class="string">"selected"</span>);</div></pre></td></tr></table></figure>
<p>使用这个方法可以更方便地为带有某些类的元素添加事件处理程序，从而不必再局限于使用ID 或标签名。<br>因为返回的对象是NodeList，所以使用这个方法与使用getElementsByTagName()以及其他返回NodeList 的DOM 方法都具有同样的性能问题。<br>支持getElementsByClassName()方法的浏览器有IE 9+、Firefox 3+、Safari 3.1+、Chrome 和Opera 9.5+。</p>
<h3 id="classList-属性"><a href="#classList-属性" class="headerlink" title="classList 属性"></a>classList 属性</h3><p>操作类名时，需要通过className 属性添加、删除和替换类名。<br>因为className 中是一个字符串，所以即使只修改字符串一部分，也必须每次都设置整个字符串的值。<br><code>&lt;div class=&quot;bd user disabled&quot;&gt;...&lt;/div&gt;</code></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//删除"user"类</span></div><div class="line"><span class="comment">//首先，取得类名字符串并拆分成数组</span></div><div class="line"><span class="keyword">var</span> classNames = div.className.split(<span class="regexp">/\s+/</span>);</div><div class="line"><span class="comment">//找到要删的类名</span></div><div class="line"><span class="keyword">var</span> pos = <span class="number">-1</span>,</div><div class="line">i,</div><div class="line">len;</div><div class="line"><span class="keyword">for</span> (i=<span class="number">0</span>, len=classNames.length; i &lt; len; i++)&#123;</div><div class="line">    <span class="keyword">if</span> (classNames[i] == <span class="string">"user"</span>)&#123;</div><div class="line">        pos = i;</div><div class="line">        <span class="keyword">break</span>;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="comment">//删除类名</span></div><div class="line">classNames.splice(i,<span class="number">1</span>);</div><div class="line"><span class="comment">//把剩下的类名拼成字符串并重新设置</span></div><div class="line">div.className = classNames.join(<span class="string">" "</span>);</div></pre></td></tr></table></figure>
<p>HTML5 新增了一种操作类名的方式，可以让操作更简单也更安全，那就是为所有元素添加classList 属性。<br>这个classList 属性是新集合类型DOMTokenList 的实例。<br>DOMTokenList 有一个表示自己包含多少元素的length 属性，而要取得每个元素可以使用item()方法，也可以使用方括号语法。</p>
<p>这个新类型还有不少方法。</p>
<ul>
<li>add(value)：将给定的字符串值添加到列表中。如果值已经存在，就不添加了。</li>
<li>contains(value)：表示列表中是否存在给定的值，如果存在则返回true，否则返回false。</li>
<li>remove(value)：从列表中删除给定的字符串。</li>
<li>toggle(value)：如果列表中已经存在给定的值，删除它；如果列表中没有给定的值，添加它。</li>
</ul>
<p><code>div.classList.remove(&quot;user&quot;);</code><br>以上代码能够确保其他类名不受此次修改的影响。其他方法也能极大地减少类似基本操作的复杂性。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//删除"disabled"类</span></div><div class="line">div.classList.remove(<span class="string">"disabled"</span>);</div><div class="line"><span class="comment">//添加"current"类</span></div><div class="line">div.classList.add(<span class="string">"current"</span>);</div><div class="line"><span class="comment">//切换"user"类</span></div><div class="line">div.classList.toggle(<span class="string">"user"</span>);</div><div class="line"><span class="comment">//确定元素中是否包含既定的类名</span></div><div class="line"><span class="keyword">if</span> (div.classList.contains(<span class="string">"bd"</span>) &amp;&amp; !div.classList.contains(<span class="string">"disabled"</span>))&#123;</div><div class="line"><span class="comment">//执行操作</span></div><div class="line">)</div><div class="line"><span class="comment">//迭代类名</span></div><div class="line"><span class="keyword">for</span> (<span class="keyword">var</span> i=<span class="number">0</span>, len=div.classList.length; i &lt; len; i++)&#123;</div><div class="line">    doSomething(div.classList[i]);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>有了classList 属性，除非你需要全部删除所有类名，或者完全重写元素的class 属性，否则也就用不到className 属性了。<br>支持classList 属性的浏览器有Firefox 3.6+和Chrome。</p>
<h2 id="焦点管理"><a href="#焦点管理" class="headerlink" title="焦点管理"></a>焦点管理</h2><p>HTML5 也添加了辅助管理DOM 焦点的功能。<br>document.activeElement 属性，这个属性始终会引用DOM 中当前获得了焦点的元素。</p>
<p>元素获得焦点的方式有页面加载、用户输入(通常是通过按Tab 键)和在代码中调用focus()方法。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> button = <span class="built_in">document</span>.getElementById(<span class="string">"myButton"</span>);</div><div class="line">button.focus();</div><div class="line">alert(<span class="built_in">document</span>.activeElement === button); <span class="comment">//true</span></div><div class="line">button.focus();</div><div class="line">alert(<span class="built_in">document</span>.hasFocus()); <span class="comment">//true</span></div></pre></td></tr></table></figure>
<p>默认情况下，文档刚刚加载完成时，document.activeElement 中保存的是document.body 元素的引用。<br>文档加载期间，document.activeElement 的值为null。</p>
<p>新增了document.hasFocus()方法，这个方法用于确定文档是否获得了焦点。<br>通过检测文档是否获得了焦点，可以知道用户是不是正在与页面交互。</p>
<p>查询文档获知哪个元素获得了焦点，以及确定文档是否获得了焦点，这两个功能最重要的用途是提高Web 应用的无障碍性。<br>无障碍Web 应用的一个主要标志就是恰当的焦点管理，而确切地知道哪个元素获得了焦点是一个极大的进步，至少我们不用再像过去那样靠猜测了。</p>
<h2 id="HTMLDocument的变化"><a href="#HTMLDocument的变化" class="headerlink" title="HTMLDocument的变化"></a>HTMLDocument的变化</h2><p>HTML5 扩展了HTMLDocument，增加了新的功能。</p>
<h3 id="readyState-属性"><a href="#readyState-属性" class="headerlink" title="readyState 属性"></a>readyState 属性</h3><p>Document 的readyState 属性有两个可能的值：</p>
<ul>
<li>loading，正在加载文档；</li>
<li>complete，已经加载完文档。</li>
</ul>
<p>使用document.readyState 的最恰当方式，就是通过它来实现一个指示文档已经加载完成的指示器。<br>在这个属性得到广泛支持之前，要实现这样一个指示器，必须借助onload 事件处理程序设置一个标签，表明文档已经加载完毕。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (<span class="built_in">document</span>.readyState == <span class="string">"complete"</span>)&#123;</div><div class="line">    <span class="comment">//执行操作</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>支持readyState 属性的浏览器有IE4+、Firefox 3.6+、Safari、Chrome 和Opera 9+。</p>
<h3 id="兼容模式"><a href="#兼容模式" class="headerlink" title="兼容模式"></a>兼容模式</h3><p>自从IE6 开始区分渲染页面的模式是标准的还是混杂的，检测页面的兼容模式就成为浏览器的必要功能。<br>IE 为此给document 添加了一个名为compatMode 的属性，这个属性就是为了告诉开发人员浏览器采用了哪种渲染模式。</p>
<p>在标准模式下，document.compatMode 的值等于”CSS1Compat”，而在混杂模式下，document.compatMode 的值等于”BackCompat”。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (<span class="built_in">document</span>.compatMode == <span class="string">"CSS1Compat"</span>)&#123;</div><div class="line">    alert(<span class="string">"Standards mode"</span>);</div><div class="line">&#125; <span class="keyword">else</span> &#123;</div><div class="line">    alert(<span class="string">"Quirks mode"</span>);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>后来，陆续实现这个属性的浏览器有Firefox、Safari 3.1+、Opera 和Chrome。最终，HTML5 也把这个属性纳入标准，对其实现做出了明确规定。</p>
<h3 id="head-属性"><a href="#head-属性" class="headerlink" title="head 属性"></a>head 属性</h3><p>HTML5 新增了document.head 属性，引用文档的<code>&lt;head&gt;</code>元素。<br>结合使用这个属性和另一种后备方法。<br><code>var head = document.head || document.getElementsByTagName(&quot;head&quot;)[0];</code><br>如果可用，就使用document.head，否则仍然使用getElementsByTagName()方法。</p>
<h2 id="字符集属性"><a href="#字符集属性" class="headerlink" title="字符集属性"></a>字符集属性</h2><p>charset 属性表示文档中实际使用的字符集，也可以用来指定新字符集。<br>默认情况下，这个属性的值为”UTF-16”，但可以通过<code>&lt;meta&gt;</code>元素、响应头部或直接设置charset 属性修改这个值。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">alert(<span class="built_in">document</span>.charset); <span class="comment">//"UTF-16"</span></div><div class="line"><span class="built_in">document</span>.charset = <span class="string">"UTF-8"</span>;</div></pre></td></tr></table></figure>
<p>defaultCharset，表示根据默认浏览器及操作系统的设置，当前文档默认的字符集应该是什么。<br>如果文档没有使用默认的字符集，那charset 和defaultCharset 属性的值可能会不一样。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (<span class="built_in">document</span>.charset != <span class="built_in">document</span>.defaultCharset)&#123;</div><div class="line">    alert(<span class="string">"Custom character set being used."</span>);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>通过这两个属性可以得到文档使用的字符编码的具体信息，也能对字符编码进行准确地控制。<br>运行适当的情况下，可以保证用户正常查看页面或使用应用。</p>
<p>支持document.charset 属性的浏览器有IE 、Firefox 、Safari 、Opera 和Chrome 。<br>支持document.defaultCharset 属性的浏览器有IE、Safari 和Chrome。</p>
<h3 id="自定义数据属性"><a href="#自定义数据属性" class="headerlink" title="自定义数据属性"></a>自定义数据属性</h3><p>HTML5 规定可以为元素添加非标准的属性，但要添加前缀data-，目的是为元素提供与渲染无关的信息，或者提供语义信息。<br>可以任意添加、随便命名，只要以data-开头即可。</p>
<p>添加了自定义属性之后，可以通过元素的dataset 属性来访问自定义属性的值。<br>dataset 属性的值是DOMStringMap 的一个实例，也就是一个名值对的映射。<br>在这个映射中，每个data-name 形式的属性都会有一个对应的属性，只不过属性名没有data-前缀(比如，自定义属性是data-myname，那映射中对应的属性就是myname)。<br><code>&lt;div id=&quot;myDiv&quot; data-appId=&quot;12345&quot; data-myname=&quot;Nicholas&quot;&gt;&lt;/div&gt;</code></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//本例中使用的方法仅用于演示</span></div><div class="line"><span class="keyword">var</span> div = <span class="built_in">document</span>.getElementById(<span class="string">"myDiv"</span>);</div><div class="line"><span class="comment">//取得自定义属性的值</span></div><div class="line"><span class="keyword">var</span> appId = div.dataset.appId;</div><div class="line"><span class="keyword">var</span> myName = div.dataset.myname;</div><div class="line"><span class="comment">//设置值</span></div><div class="line">div.dataset.appId = <span class="number">23456</span>;</div><div class="line">div.dataset.myname = <span class="string">"Michael"</span>;</div><div class="line"><span class="comment">//有没有"myname"值呢？</span></div><div class="line"><span class="keyword">if</span> (div.dataset.myname)&#123;</div><div class="line">    alert(<span class="string">"Hello, "</span> + div.dataset.myname);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>如果需要给元素添加一些不可见的数据以便进行其他处理，那就要用到自定义数据属性。<br>在跟踪链接或混搭应用中，通过自定义数据属性能方便地知道点击来自页面中的哪个部分。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Web/" rel="tag"># Web</a>
          
            <a href="/tags/JavaScript/" rel="tag"># JavaScript</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/10/04/javascript-note-10-5/" rel="next" title="《 JavaScript 高级程序设计》备忘-第十章-5">
                <i class="fa fa-chevron-left"></i> 《 JavaScript 高级程序设计》备忘-第十章-5
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/10/05/javascript-note-11-2/" rel="prev" title="《 JavaScript 高级程序设计》备忘-第十一章-2">
                《 JavaScript 高级程序设计》备忘-第十一章-2 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/avatar.jpg"
               alt="Huang SJ" />
          <p class="site-author-name" itemprop="name">Huang SJ</p>
          <p class="site-description motion-element" itemprop="description"></p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">75</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">9</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/hsj1992" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/hsj9527" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/u/1694147905" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  Weibo
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.freecodecamp.cn/hsj1992" target="_blank" title="FreeCodeCamp">
                  
                    <i class="fa fa-fw fa-fire"></i>
                  
                  FreeCodeCamp
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://codepen.io/hsj1992/" target="_blank" title="codepen">
                  
                    <i class="fa fa-fw fa-codepen"></i>
                  
                  codepen
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://hsj1992.oschina.io/" target="_blank" title="码云镜像">
                  
                    <i class="fa fa-fw fa-code"></i>
                  
                  码云镜像
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://hsj1992.coding.me/" target="_blank" title="coding镜像">
                  
                    <i class="fa fa-fw fa-code"></i>
                  
                  coding镜像
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://hsj1992.github.io/" target="_blank" title="github镜像">
                  
                    <i class="fa fa-fw fa-code"></i>
                  
                  github镜像
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://codingme-6dd8a.firebaseapp.com" target="_blank" title="Firebase镜像">
                  
                    <i class="fa fa-fw fa-google"></i>
                  
                  Firebase镜像
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#选择符API"><span class="nav-number">1.</span> <span class="nav-text">选择符API</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#querySelector-方法"><span class="nav-number">1.1.</span> <span class="nav-text">querySelector()方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#querySelectorAll-方法"><span class="nav-number">1.2.</span> <span class="nav-text">querySelectorAll()方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#matchesSelector-方法"><span class="nav-number">1.3.</span> <span class="nav-text">matchesSelector()方法</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#元素遍历"><span class="nav-number">2.</span> <span class="nav-text">元素遍历</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#HTML5"><span class="nav-number">3.</span> <span class="nav-text">HTML5</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#与类相关的扩充"><span class="nav-number">3.1.</span> <span class="nav-text">与类相关的扩充</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#getElementsByClassName-方法"><span class="nav-number">3.1.1.</span> <span class="nav-text">getElementsByClassName()方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#classList-属性"><span class="nav-number">3.1.2.</span> <span class="nav-text">classList 属性</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#焦点管理"><span class="nav-number">3.2.</span> <span class="nav-text">焦点管理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#HTMLDocument的变化"><span class="nav-number">3.3.</span> <span class="nav-text">HTMLDocument的变化</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#readyState-属性"><span class="nav-number">3.3.1.</span> <span class="nav-text">readyState 属性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#兼容模式"><span class="nav-number">3.3.2.</span> <span class="nav-text">兼容模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#head-属性"><span class="nav-number">3.3.3.</span> <span class="nav-text">head 属性</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#字符集属性"><span class="nav-number">3.4.</span> <span class="nav-text">字符集属性</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#自定义数据属性"><span class="nav-number">3.4.1.</span> <span class="nav-text">自定义数据属性</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Huang SJ</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="//cdn.staticfile.org/jquery/2.1.3/jquery.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/fastclick/1.0.6/fastclick.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/jquery_lazyload/1.9.7/jquery.lazyload.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/velocity/1.2.1/velocity.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/velocity/1.2.1/velocity.ui.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/fancybox/2.1.5/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  

  


</body>
</html>
